package cn.shadow.aop;

import cn.shadow.aop.advisor.Advisor;
import cn.shadow.beans.BeanFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;


/**
 * jdk的代理部分
 * @author notto
 */
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {

    private String beanName;

    private Object target;

    private List<Advisor> advisorList;

    private BeanFactory beanFactory;

    public JdkDynamicAopProxy(String beanName, Object target, List<Advisor> advisorList, BeanFactory beanFactory) {
        super();
        this.beanName = beanName;
        this.target = target;
        this.advisorList = advisorList;
        this.beanFactory = beanFactory;
    }

    @Override
    public Object getProxy() {
        return getProxy(target.getClass().getClassLoader());
    }

    @Override
    public Object getProxy(ClassLoader classLoader) {
        return Proxy.newProxyInstance(classLoader, target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return AopProxyUtil.applyAdvice(target, method, args, advisorList, proxy, beanFactory);
    }
}
